import React, { useState } from 'react';
// import { Form, Switch, Popover, Button, TreeSelect, Select, message, Spin } from 'antd';
import { Form, Switch, Popover, Button, Select, message, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks/';
// import { saveSet, getChannelColumns, getEmailTemplateListSimple } from '../../service';
import { saveSet, getEmailTemplateListSimple } from '../../service';
import styles from './index.less';

const { Option } = Select;

const CHANNEL = {
    INTERNAL: 1,
    EXTERNAL: 2,
    HUNTING: 3
};

const ChannelSetPopover = ({ form, children, type, data, onSuccess, ...restProps }) => {
    const { getFieldDecorator, resetFields } = form;
    const [visible, setVisible] = useState(false);

    // 获取渠道列表
    // const { data: channelColumns, loading: columnsLoading, run: fetchChannelColumns } = useRequest(getChannelColumns, {
    //     manual: true,
    //     initialData: [],
    //     formatResult: result => {
    //         const { code, data: resData, msg } = result;
    //         if (code === 10000) {
    //             return resData?.map(item => ({
    //                 title: item.columnName,
    //                 value: item.columnCode,
    //                 disabled: item.columnCode === 'positionName'
    //             }));
    //         }
    //         message.error(msg);
    //         return [];
    //     }
    // });

    // 保存设置
    const { loading: saveLoading, run: handleSave } = useRequest(value => saveSet({ ...value, id: data?.id }), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                if (onSuccess) {
                    onSuccess(type);
                }
                setVisible(false);
                resetFields();
            } else {
                message.error(msg);
            }
        }
    });

    const { data: emailList, loading: emailLoading, run: fetchEmailList } = useRequest(getEmailTemplateListSimple, {
        manual: true,
        initialData: [],
        ...defaultFormatResult
    });

    // 提交表单
    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { autoReleaseSwitch, channelStatus, disableShowSwitch } = values;
                handleSave({
                    ...values,
                    autoReleaseSwitch: autoReleaseSwitch ? 1 : 0,
                    channelStatus: channelStatus ? 1 : 0,
                    disableShowSwitch: disableShowSwitch ? 1 : 0
                });
            }
        });
    };

    // 取消
    const handleCancel = () => {
        setVisible(false);
        resetFields();
    };

    const handleVisibleChange = value => {
        setVisible(value);
    };

    React.useEffect(() => {
        // if (visible && type === CHANNEL.INTERNAL && channelColumns?.length === 0) {
        //     fetchChannelColumns();
        // }
        if (visible && type === CHANNEL.HUNTING && emailList?.length === 0) {
            fetchEmailList();
        }
    }, [visible]);

    const renderSelect = templateType => {
        if (emailList && emailList.length > 0) {
            return emailList
                .filter(item => item.templateType === templateType)
                .map(item => (
                    <Option key={item.id} value={item.id}>
                        {item.templateName}
                    </Option>
                ));
        }
        return null;
    };

    // const defaultColumns = React.useMemo(() => {
    //     const filterOut = ['salaryRange'];
    //     return channelColumns?.filter(item => !filterOut.includes(item.value)).map(item => item.value) || undefined;
    // }, [channelColumns]);

    // const getColumns = arr => {
    //     if (arr && arr.length > 0) {
    //         return channelColumns.filter(item => arr.includes(item.value)).map(item => item.value);
    //     }
    //     return undefined;
    // };

    // 渲染设置弹窗
    const renderForm = () => {
        // if (type === CHANNEL.INTERNAL) {
        //     return (
        //         <Form.Item label="岗位信息发布字段">
        //             <Spin spinning={columnsLoading}>
        //                 {getFieldDecorator('dutyReleaseColumns', {
        //                     initialValue:
        //                         data?.dutyReleaseColumns?.length > 0
        //                             ? getColumns(data?.dutyReleaseColumns)
        //                             : defaultColumns
        //                 })(
        //                     <TreeSelect
        //                         showSearch={false}
        //                         treeData={channelColumns || []}
        //                         treeCheckable
        //                         showCheckedStrategy={TreeSelect.SHOW_PARENT}
        //                         placeholder="请选择岗位信息发布字段"
        //                         style={{
        //                             width: '100%'
        //                         }}
        //                         maxTagCount={3}
        //                     />
        //                 )}
        //             </Spin>
        //         </Form.Item>
        //     );
        // }
        if (type === CHANNEL.HUNTING) {
            return (
                <>
                    <Form.Item label="岗位发布/上线时发送邮件模版：">
                        <Spin spinning={emailLoading}>
                            {getFieldDecorator('onlineMailTemplateId', {
                                initialValue: data?.onlineMailTemplateId || undefined
                            })(
                                <Select placeholder="请选择" allowClear>
                                    {renderSelect(1)}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="岗位更新时发送邮件模版：">
                        <Spin spinning={emailLoading}>
                            {getFieldDecorator('toupdateMailTemplateId', {
                                initialValue: data?.toupdateMailTemplateId || undefined
                            })(
                                <Select placeholder="请选择" allowClear>
                                    {renderSelect(2)}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="岗位下线时发送邮件模版：">
                        <Spin spinning={emailLoading}>
                            {getFieldDecorator('offlineMailTemplateId', {
                                initialValue: data?.offlineMailTemplateId || undefined
                            })(
                                <Select placeholder="请选择" allowClear>
                                    {renderSelect(3)}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                </>
            );
        }
        return null;
    };

    const content = (
        <>
            <Form className={styles.formWrap} style={{ marginTop: 12, width: '480px' }}>
                <Form.Item label="启用渠道">
                    {getFieldDecorator('channelStatus', {
                        valuePropName: 'checked',
                        initialValue: !!data?.channelStatus
                    })(<Switch size="small" />)}
                </Form.Item>
                <Form.Item label="自动发布">
                    {getFieldDecorator('autoReleaseSwitch', {
                        valuePropName: 'checked',
                        initialValue: !!data?.autoReleaseSwitch
                    })(<Switch size="small" />)}
                </Form.Item>
                <Form.Item label="被禁用后在渠道发布中显示">
                    {getFieldDecorator('disableShowSwitch', {
                        valuePropName: 'checked',
                        initialValue: !!data?.disableShowSwitch
                    })(<Switch size="small" />)}
                </Form.Item>
                {renderForm()}
            </Form>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button size="small" style={{ marginRight: 8 }} onClick={handleCancel}>
                    取消
                </Button>
                <Button size="small" type="primary" loading={saveLoading} onClick={handleSubmit}>
                    确定
                </Button>
            </div>
        </>
    );

    return (
        <Popover
            title="设置"
            content={content}
            trigger="click"
            placement="left"
            visible={visible}
            arrowPointAtCenter
            onVisibleChange={handleVisibleChange}
            getPopupContainer={trigger => trigger.parentElement}
            {...restProps}
        >
            {children}
        </Popover>
    );
};

export default Form.create({})(ChannelSetPopover);
